﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MethodWorx.CMS.UI.Models;
using MethodWorx.CMS.Plugins;
using MethodWorx.CMS.Configuration;

namespace MethodWorx.CMS.UI.Application
{
    public class PropertyDetailsModelBinder : IModelBinder
    {

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            PropertyConfiguration pc = new PropertyConfiguration();

            ModelBindingContext context = new ModelBindingContext();

            PropertyDetails<object> details = (PropertyDetails<object>)System.Web.Mvc.ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
            foreach (var configuration in pc.GetPropertyConfigurations())
            {
                if ((details.Type ?? string.Empty).ToLower() == configuration.Name.ToLower())
                {
                    bindingContext.ModelMetadata = new DataAnnotationsModelMetadata(new DataAnnotationsModelMetadataProvider(), null, null, typeof(PropertyDetails<>).MakeGenericType(configuration.GetDetailsType()), bindingContext.ModelName, null);
                    object model = System.Web.Mvc.ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
                    details.Custom = (ICustomPropertyDetails)model.GetType().InvokeMember("Custom", System.Reflection.BindingFlags.GetProperty, null, model, null);
                }
            }

            return details;
        }
    }
}